# -*- coding: utf-8 -*-
import json
from datetime import datetime
from scrapy.utils.project import get_project_settings
from cnncmall.items import cnncmallItem,cnncmallSku
from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.util.encrypt_util import build_sha1_order_id, md5, short_uuid
from zc_core.util.common import parse_time, parse_timestamp, parse_number

def parse_catalog(response):
    cat_list = list()
    todo_cat_list = list()
    settings = get_project_settings()
    white_list = settings.get('CATALOG_WHITE_LIST', [])
    cat_json = json.loads(response.text)
    cat1_list_js = cat_json.get('data', {}).get('guideCatalogBOS', [])
    for cat1_js in cat1_list_js:
        cat1 = build_catalog(cat1_js, '', 1)
        cat1_id = cat1.get('catalogId')
        cat_list.append(cat1)
        todo = False
        if cat1_id in white_list:
            todo = True
        cat2_list_js = cat1_js.get('rows', [])
        for cat2_js in cat2_list_js:
            cat2 = build_catalog(cat2_js, cat1_id, 2)
            cat2_id = cat2.get('catalogId')
            cat_list.append(cat2)
            cat3_list_js = cat2_js.get('rows', [])
            for cat3_js in cat3_list_js:
                cat3 = build_catalog(cat3_js, cat2_id, 3)
                cat_list.append(cat3)
                if todo:
                    todo_cat_list.append(cat3)
    return cat_list, todo_cat_list


def build_catalog(cat, pid, level):
    entity = Catalog()
    entity['catalogId'] = str(cat.get('guideCatalogId'))
    entity['catalogName'] = cat.get('catalogName')
    entity['parentId'] = str(pid)
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 1

    return entity


def parse_query_info(response):
    rs = json.loads(response.text)
    data = rs.get("data", {})

    vendor_list = []
    brand_list = []
    for item in data.get('queryParams', []):
        if item and item.get('filterId', '') == 'brand_id_name':
            brand_list = item.get('filterValues', [])
        if item and item.get('filterId', '') == 'vendor_id_name':
            vendor_list = item.get('filterValues', [])
    return vendor_list, brand_list


def parse_total_page(response):
    rs = json.loads(response.text)
    total = rs.get("data", {}).get('total', 0)
    return total


def parse_sku_list(response):
    cat_helper = CatalogHelper()
    meta = response.meta
    cat3_id = meta.get("cat3Id")
    rs = json.loads(response.text)
    sku_list = list()
    item_list = list()

    rows = rs.get("data", {}).get('result', {})
    for row in rows:
        sku = cnncmallSku()
        sku['skuId'] = str(row.get('skuId'))
        brand_name = row.get('brandName', '')
        if brand_name:
            sku['brandId'] = md5(brand_name)
        sku['catalog3Id'] = cat3_id
        sku['supplierId'] = str(row.get('supplierId', ''))
        sku['traceId']=rs.get('data',{}).get('traceId')
        sku_list.append(sku)

        item = cnncmallItem()
        item['skuId'] = str(row.get('skuId'))
        item['skuCode'] = str(row.get('commodityId'))
        item['skuName'] = row.get('skuName')
        item['traceId'] = rs.get('data', {}).get('traceId')
        brand_name = row.get('brandName', '')
        if brand_name:
            item['brandId'] = md5(brand_name)
            item['brandName'] = brand_name
        item['catalog3Id'] = cat3_id
        cat_helper.fill(item)
        item['supplierId'] = str(row.get('supplierId', ''))
        item['supplierName'] = row.get('supplierName', '')
        sp_sku_id = str(row.get('extSkuId', ''))
        if sp_sku_id:
            item['supplierSkuId'] = sp_sku_id
            plat_code = None
            if item['supplierId'] == '100059' or '得力' in item['supplierName']:
                plat_code = 'deli'
            item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
        item['skuImg'] = row.get('priPicUrl', '')
        item_list.append(item)

    return sku_list, item_list


def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get("skuId")
    sp_id = meta.get("supplierId")

    js = json.loads(response.text)
    if js and js.get('data', {}):
        data = js.get('data', {})
        sales = data.get('skuInfoSaleNumBO', {})
        detail = data.get('commdDetailsInfo', {})
        if detail:
            sku = detail.get('skuInfo', {})
            commd_info = detail.get('commdInfo', {}).get('notJdCommdDetails', {})
            if not commd_info:
                commd_info = detail.get('commdInfo', {}).get('jdCommdInfo', {})
            item = cnncmallItem()
            item['batchNo'] = batch_no
            item['skuId'] = str(sku_id)
            item['skuCode'] = str(sku.get('commodityId'))
            item['skuName'] = sku.get('skuName')
            item['brandId'] = sku.get('brandId', '')
            item['brandName'] = sku.get('brandName', '')
            item['brandModel'] = commd_info.get('mfgSku', '')
            item['catalog3Id'] = sku.get('catalogId', '')
            item['supplierId'] = sku.get('supplierShopId', '') or sp_id
            item['supplierName'] = sku.get('shopName', '')
            item['materialCode'] = sku.get('materialId', '')
            sp_sku_id = str(sku.get('extSkuId', ''))
            if sp_sku_id:
                item['supplierSkuId'] = sp_sku_id
                plat_code = None
                if item['supplierId'] == '100059' or '得力' in item['supplierName']:
                    plat_code = 'deli'
                item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
            item['barCode'] = sku.get('upcCode', '')
            if commd_info:
                item['unit'] = commd_info.get('saleUnit', '')
                item['minBuy'] = commd_info.get('moq', '')
                item['skuImg'] = commd_info.get('imagePath', '')
            if sales:
                sold_count = sales.get('soldNumber', '')
                if sold_count < 0:
                    sold_count = 0
                item['soldCount'] = sold_count
            item['genTime'] = datetime.utcnow()
            return item


def parse_price_list(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    rs = json.loads(response.text)
    item_list = list()

    data = rs.get("data", {})
    if data:
        price_info = data.get('commdPriceInfo', {})
        if price_info:
            not_jd_rows = price_info.get('notJdPriceInfo', [])
            if not_jd_rows:
                for row in not_jd_rows:
                    item = ItemData()
                    item['batchNo'] = batch_no
                    item['skuId'] = str(row.get('skuId', ''))
                    item['salePrice'] = parse_number(row.get('price', ''))
                    item['originPrice'] = parse_number(row.get('marketPrice', ''))
                    item_list.append(item)
            jd_rows = price_info.get('jdPriceInfos', [])
            if jd_rows:
                for row in jd_rows:
                    item = ItemData()
                    item['batchNo'] = batch_no
                    item['skuId'] = str(row.get('skuId', ''))
                    item['salePrice'] = parse_number(row.get('price', ''))
                    item['originPrice'] = parse_number(row.get('marketPrice', ''))
                    item_list.append(item)
    return item_list


# 解析group关系
def parse_group(response):
    meta = response.meta
    batch_no = meta.get("batchNo")
    sku_id = meta.get('skuId')
    rs = json.loads(response.text)
    data = rs.get('data', {})
    ids = list()
    if data:
        group = ItemGroup()
        spu_id = short_uuid()
        group['batchNo'] = batch_no
        group['spuId'] = spu_id
        group['skuId'] = sku_id
        group['skuIdList'] = ids
        ids.append(sku_id)
        rows = data.get('rows', [])
        for same_sku in rows:
            same_sku_id = str(same_sku.get("skuId"))
            ids.append(same_sku_id)
        return group, ids
